/**
 * 项目数据源配置表管理初始化
 */
var SdsDataConfig = {
    id: "SdsDataConfigTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    zTree: null,
    cfgIndex: 1,
    layerIndex: -1,
    linkFlag: false,
    itemDicId: "",
    dataConfigData:  {}			//字典
};

/**
 * 查询项目数据源配置表列表
 */
SdsDataConfig.search = function () {
    SdsDataConfig.InitdicArea();
};

/**
 *初始化数据源配置表单
 */
SdsDataConfig.initSourceForm = function (inputID){
    SdsDataConfig.clearData();
    //查询数据源配置信息
    var params = {};
    params.fitemId = $("#formItemId").val();
    params.itemDicId = inputID;
    var configs = null;
    var ajax = new $ax(Sys.backendPath + "/sds/sdsdataconfig/configList", function(data){
        configs = data;
    },function (data){
        $("#addBtn").click();
    });
    ajax.setData(params);
    ajax.start();

    $("#configCnt").text(configs.length)
    if (configs == null || configs.length == 0) {
        $("#addBtn").click();
        return
    } else {
        for (var i = 0, l = configs.length; i < l; i++) {
            SdsDataConfig.cfgIndex = i + 1;
            var config = configs[i];
            $('#acc').accordion('add', {
                id: config.id,
                title: '数据源-' + SdsDataConfig.cfgIndex,
                iconCls: 'icon-w-config',
                content: SdsDataConfig.creatDataArea(),
                selected: i == 0
            });
        }
    }
}

/**
 * 清除数据
 */
SdsDataConfig.clearData = function() {
    this.dataConfigData = {};
    $("#configCnt").text(0);
    // 清楚手风琴内容
    var stage = $('#acc').accordion('panels');
    for (var index = stage.length - 1; index > -1; index--) {
        $('#acc').accordion('remove', index);
    }
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
SdsDataConfig.set = function(key, value) {
    this.dataConfigData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
SdsDataConfig.get = function(key) {
    return $("#" + key).val();
}

/**
 * 收集添加数据源字典的数据
 */
SdsDataConfig.collectData = function (idx) {
    this.set('dsId',$('#dsId_'+idx).combotree('getValue')).set('btIsCache', $("#btIsCache_"+idx).switchbox('getValue')?1:0)
        .set('linkStandId',$('#linkStandId_'+idx).combotree('getValue')).set('calcExp', encodeURIComponent($('#calcExp_'+idx).val()))
        .set('getTiming',$('#getTiming_'+idx).combobox('getValue')).set('valueItemCode',$('#valueItemCode_'+idx).val())
        .set('id',$("#configId_"+idx).val()).set('fitemId',$("#formItemId").val()).set('fitemDicId',SdsDataConfig.itemDicId);;
};

/**
 * 提交修改
 */
SdsDataConfig.editSubmit = function (obj) {
    var ButtonText=$('#ConfigType')[0].innerText
    if (ButtonText.indexOf("项目")>0&&SdsDataConfig.itemDicId == "") {
        $.messager.popover({msg: '请选择一个值域项进行配置！', type: 'info', timeout: 2000, showType: 'slide'});
        return
    }

    var configIndex = $(obj).attr("id").split("_")[1];
    if ($('#dsId_'+configIndex).combotree('getValue') == "") {
        $.messager.popover({msg: '请选择数据源进行配置！', type: 'info', timeout: 2000, showType: 'slide'});
        return
    }
    this.collectData(configIndex);
    var ajax = new $ax(Sys.backendPath + "/sds/sdsdataconfig/edit", function (data) {
        SdsDataConfig.initSourceForm(SdsDataConfig.itemDicId);
        Sys.success("配置成功!");
    }, function (data) {
        Sys.error("配置失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.dataConfigData);
    ajax.start();
};

SdsDataConfig.deleteConfig = function (obj) {
    $.messager.confirm("重置", "是否重置该条数据配置信息?", function (r) {
        if (r) {
            var configIndex = $(obj).attr("id").split("_")[1];
            var configId = $("#configId_"+configIndex).val();
            var ajax = new $ax(Sys.backendPath + "/sds/sdsdataconfig/delete", function (data) {
                Sys.success("重置成功!");
                SdsDataConfig.initSourceForm(SdsDataConfig.itemDicId);
            }, function (data) {
                Sys.error("重置失败!" + data.responseJSON.message + "!");
            });
            ajax.set('sdsDataConfigId',configId);
            ajax.start();
        }
    })
}

SdsDataConfig.InitdicArea=function(){
    SdsDataConfig.itemDicId="";
    //清空字典配置
    $('#ConfigType').linkbutton({text:'按字典配置'});
    $('#dicArea').css({'display':'none'});
    //初始化项目配置
    SdsDataConfig.initSourceForm();
}

SdsDataConfig.reloadConfig=function(DicId){
    SdsDataConfig.initSourceForm(DicId);
    SdsDataConfig.itemDicId=DicId;
}

SdsDataConfig.changeSource = function(sourceId, idx) {
    // var sourceId = source.id;
    $HUI.combotree('#linkStandId_'+idx,{
        url: '/sds/sdsstanddic/getDicTree/'+sourceId
    });
}

//单选字典
SdsDataConfig.CreatSDDic=function() {
    $("#itemDicId").combobox({
        valueField:'id',
        textField:'desc',
        mode:'remote',
        url:"/sds/sdsqcfitemdic/itemDics/"+$("#formItemId").val(),
        onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
            var val = $(this).combobox("getData");
            if (val.length) {
                $(this).combobox("setValue", val[0].id);
            }
        },
        onChange:function(newval,oldval){
            SdsDataConfig.itemDicId = newval;
            SdsDataConfig.initSourceForm(newval);
        }
    });
    $("#dicArea").css('display', 'block');
}

SdsDataConfig.creatDataArea=function () {
    var _html = '';
    _html +="<div title=\"数据源-"+SdsDataConfig.cfgIndex+"\" data-options=\"iconCls:'icon-w-config'\" style=\"overflow:auto;padding:10px;\">\n" +
        "            <input type=\"hidden\" id=\"configId_"+SdsDataConfig.cfgIndex+"\" name=\"configId\"/>" +
        "            <div class=\"row btn-margin-bottom\" style=\"margin-right: 0px !important;\">\n" +
        "                <span class=\"col-sm-1\" style=\"margin-top:5px;text-align: right\">数据源</span>\n" +
        "                <div class=\"col-sm-9\">\n" +
        "                    <input id=\"dsId_"+SdsDataConfig.cfgIndex+"\" name=\"dsId\" class=\"hisui-combotree\" data-options=\"url:'/sds/sdsstanddatasource/getDataSourceTree',editable:true,onSelect:function(event,value){ SdsDataConfig.changeSource(event.id, " + SdsDataConfig.cfgIndex + ")}\" placeholder='请点击下拉' style=\"width:545px;\"/>\n" +
        "                </div>\n" +
        "            </div>\n" +
        "            <div class=\"row btn-margin-bottom\" style=\"margin-right: 0px !important;\">\n" +
        "                <span class=\"col-sm-1\" style=\"margin-top:5px;text-align: right\">标准字典</span>\n" +
        "                <div class=\"col-sm-9\">\n" +
        "                    <input id=\"linkStandId_"+SdsDataConfig.cfgIndex+"\" name=\"linkStandId\" class=\"hisui-combotree\" data-options=\"url: '/sds/sdsstanddic/getDicTree/0',editable:true\" placeholder='请点击下拉' style=\"width:545px;\"/>\n" +
        "                </div>\n" +
        "            </div>\n" +
        "            <div class=\"row btn-margin-bottom\" style=\"margin-right: 0px !important;\">\n" +
        "                <span class=\"col-sm-1 control-span\">采集时机</span>\n" +
        "                <div class=\"col-sm-4\">\n" +
        "                    <select class=\"hisui-combobox textbox\" id=\"getTiming_"+SdsDataConfig.cfgIndex+"\" name=\"getTiming\"\n" +
        "                            data-options=\"editable:false,multiple:false,allowNull:true,selectOnNavigation:false,valueField:'id',textField:'text',url:'/sds/common/dicListByTypeCode/ItemGetValTime'\">\n" +
        "                    </select>\n" +
        "                </div>\n" +
        "                <span class=\"col-sm-1\" style=\"margin-top:5px;text-align: right\">关联取值代码</span>\n" +
        "                <div class=\"col-sm-4\">\n" +
        "                    <input class=\"hisui-textbox textbox\" style=\"width: 155px; height: 30px;\" id=\"valueItemCode_"+SdsDataConfig.cfgIndex+"\" name=\"valueItemCode\">\n" +
        "                </div>\n" +
        "            </div>\n" +
        "            <div class=\"row btn-margin-bottom\" style=\"margin-right: 0px !important;\">\n" +
        "                <span class=\"col-sm-1\" style=\"margin-top:0px;text-align: right\">是否缓存</span>\n" +
        "                <div class=\"col-sm-4\">\n" +
        "                    <div class='hisui-switchbox' id=\"btIsCache_"+SdsDataConfig.cfgIndex+"\" data-options=\"onText:'是',offText:'否',size:'mini',animated:true,onClass:'primary',offClass:'gray',checked:false\" name=\"btIsCache\">\</div>\n" +
        "                </div>\n" +
        "            </div>\n" +
        "            <div class=\"row \" style=\"margin-right: 0px !important;\">\n" +
        "                <span class=\"col-sm-1  control-span\">逻辑运算</span>\n" +
        "                <div class=\"col-sm-9\">\n" +
        "                    <input class=\"hisui-textbox textbox\" id=\"calcExp_"+SdsDataConfig.cfgIndex+"\" name=\"calcExp_\" style=\"width:97%;\">\n" +
        "                </div>\n" +
        "            </div>\n" +
        "            <div class=\"toolbar\"\n" +
        "                 style=\"text-align: center;position: absolute;margin-top: 20px;left: 50%;transform: translateX(-50%);\">\n" +
        "                <button type=\"button\" data-toggle=\"tooltip\" title=\"保存\" id=\"dataConfigButton_"+SdsDataConfig.cfgIndex+"\" class=\"hisui-linkbutton\" onclick=\"SdsDataConfig.editSubmit(this)\">保存</button>\n" +
        "                <button type=\"button\" data-toggle=\"tooltip\" title=\"重置\" id=\"resetConfigButton_"+SdsDataConfig.cfgIndex+"\" class=\"hisui-linkbutton\" onclick=\"SdsDataConfig.deleteConfig(this)\">重置</button>" +
        "            </div>\n" +
        "        </div>"
    return _html;
}

$(function() {

    $('#ConfigType').on('click', function(){
        var ButtonText=$('#ConfigType')[0].innerText
        if (ButtonText.indexOf("字典")>0) {
            $('#ConfigType').linkbutton({text:'按项目配置'});
            SdsDataConfig.clearData();   //按字典配置时，清空项目配置数据
            SdsDataConfig.CreatSDDic();
            $('#dicArea').css({'display':'block'});
        }else{
            SdsDataConfig.InitdicArea();
        }
    });

    var accObj = $HUI.accordion("#acc");
    //阶段选择
    $('#acc').accordion({
        onSelect:function(title,index){
            var that = accObj.getSelected();
            if (!that) return;
            var configId = that.attr("id");
            if (!configId) {
                return;
            }
            that.panel('refresh');// 先刷新再赋值，要不然找不到元素
            var ajax = new $ax(Sys.backendPath + "/sds/sdsdataconfig/config/"+configId, function (data) {
                var config = data;
                index = index+1;
                $("#configId_"+index).val(config.id);
                $("#dsId_"+index).combotree('setValue',config.dsId);
                $("#linkStandId_"+index).combotree('setValue',config.linkStandId);
                $("#getTiming_"+index).combobox("select", config.getTiming);
                $("#calcExp_"+index).val(config.calcExp);
                $("#valueItemCode_"+index).val(config.valueItemCode);
                if (config.btIsCache == 1){
                    $("#btIsCache_"+index).switchbox("setValue", true);
                }
            }, function (data) {
                Sys.error("获取配置失败!" + data.responseJSON.message + "!");
            });
            ajax.start();
        }
    });

    $HUI.linkbutton("#addBtn",{
        onClick:function(){
            var accPanelLength = $("#acc .panel").length;
            if (accPanelLength >= 3) {
                $.messager.popover({msg: '最多配置3个数据源！', type: 'info', timeout: 2000, showType: 'slide'});
                return
            }
            SdsDataConfig.cfgIndex = accPanelLength + 1;
            accObj.add({
                title:'数据源-'+SdsDataConfig.cfgIndex,
                iconCls:'icon-w-config',
                content:SdsDataConfig.creatDataArea(),
                selected:true
            });
        }
    });

    $HUI.linkbutton("#removeBtn",{
        onClick:function(){
            var accPanelLength = $("#acc .panel").length;
            // 删除当前选中的
            var p = accObj.getSelected();
            if (p){
                var configId = p.attr("id");
                if (configId) {
                    $.messager.popover({msg: '当前非新增配置不能删除,请重置！', type: 'info', timeout: 2000, showType: 'slide'});
                    return;
                }
                var index = accObj.getPanelIndex(p);
                accObj.remove(index);
            } else {
                $.messager.popover({msg: '请选择一个数据源配置进行删除！', type: 'info', timeout: 2000, showType: 'slide'});
                return
            }
            var i = 1;
            $("#acc .panel").each(function (){
                $(this).find('.panel-title').text('数据源-'+ i);
                i++;
            })
            SdsDataConfig.cfgIndex--;
        }
    })
});

/**
 * combobox和combotree模糊查询
 */
(function(){
    /**
     * 根据叶子节点展开所有父节点
     * @param treeObj 树对象，（combotree的树对象获取：var treeObj = comboObj.combotree("tree");）
     * @param node 叶子节点
     */
    function expandParent(treeObj, node){
        var parentNode = treeObj.tree("getParent", node.target);
        if(parentNode != null && parentNode != "undefined"){
            treeObj.tree("expand", parentNode.target);
            expandParent(treeObj, parentNode);
        }
    };

    //combotree可编辑，自定义模糊查询
    $.fn.combotree.defaults.editable = true;
    $.extend($.fn.combotree.defaults.keyHandler,{
        up:function(){
            // console.log('up');
        },
        down:function(){
            // console.log('down');
        },
        enter:function(){
            // console.log('enter');
        },
        query:function(q){
            var t = $(this).combotree('tree');
            var nodes = t.tree('getChildren');
            for(var i=0; i<nodes.length; i++){
                var node = nodes[i];
                if (node.text.indexOf(q) >= 0){
                    $(node.target).show();
                    expandParent(t, node);
                } else {
                    $(node.target).hide();
                }
            }
            var opts = $(this).combotree('options');
            if (!opts.hasSetEvents){
                opts.hasSetEvents = true;
                var onShowPanel = opts.onShowPanel;
                opts.onShowPanel = function(){
                    var nodes = t.tree('getChildren');
                    for(var i=0; i<nodes.length; i++){
                        $(nodes[i].target).show();
                    }
                    onShowPanel.call(this);
                };
                $(this).combo('options').onShowPanel = opts.onShowPanel;
            }
        }
    });
})(jQuery);
